

#  Spending by Predicted Mortality for Different Age Groups -----------



monthly_cost_ageQ_func <- function(data, group_txt, min = min_obs_num) {
  output_dt <- 
    data[
      ,
      .(group = group_txt,
        ave_monthly_cost = (sum(UTL_f365d_total_cost)/sum(num_days_lived))*31,
        obs_num = .N),
      by = .(deciles = plyr::round_any(prob_for_report, 0.1, ceiling),
             DMG_age_quintiles)
      ][obs_num >= min]
  return(output_dt)
}


MonthlySpending_byPhat_andDeath_ageQ<- function(data = dt_for_exhibits_cancer) {


dt_monthly_cost_ageQ <- rbind(
  monthly_cost_ageQ_func(data[DMG_died_within_365d == "1"],
                         "Decedent"),
  monthly_cost_ageQ_func(data[DMG_died_within_365d == "0"],
                         "Survivor")
)

if (sum(dt_monthly_cost_ageQ$obs_num)/
    nrow(data)<0.99) {
  stop("Problem with building dt for figure 7!")
}

write.csv(dt_monthly_cost_ageQ,
          file = "MonthlySpending_byPhat_andDeath_ageQ.csv") 


pdf(file = "MonthlySpending_byPhat_andDeath_ageQ.pdf", width = 10, height = 7.5) 
print(ggplot(
  data = dt_monthly_cost_ageQ,
  aes(x=deciles, y=ave_monthly_cost, linetype=group)
) + 
  geom_line(size=1) +
  facet_grid(~DMG_age_quintiles) +
  scale_x_continuous(breaks = seq(0, 1, 0.2)) +
  scale_y_continuous(labels = scales::comma) +
  scale_linetype_manual(values = c("dashed","solid"))+
  expand_limits(y=0) +
  labs(x = "Initial Prognosis (One-Year Mortality Risk)", 
       y = "Average Monthly Spending (NIS)",
       subtitle = "Age Group",
       linetype = "") +
  theme(axis.text.x = element_text(angle=90), 
        aspect.ratio = 2,
        legend.key = element_rect(fill="white"),
        legend.position = "bottom",
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16),
        plot.subtitle = element_text(size = 16))
)
dev.off()
}
